import { defineStore } from 'pinia'
import { ShopDataStore } from './state'
import Storage from '@/utils/storage'
import shopData from './state'

export const useshopDataStore = defineStore('shopDataStore', {
    state: () => shopData,
    actions: {
        SET_SHOP_DATA(payload: ShopDataStore) {
            this.shopData = Object.assign(this.shopData, payload)
            Storage.set('shopData', this.shopData, 60 * 60 * 24)
        },
        DEL_SHOP_DATA() {
            this.shopData = {
                id: '',
                createTime: '',
                updateTime: '',
                version: 0,
                deleted: false,
                shopId: '',
                total: '',
                undrawn: '',
                uncompleted: '',
                amountToBeAudited: '',
            }
            Storage.remove('shopData')
        },
    },
    getters: {
        gettershopData: (state) => {
            return getshopDataFn(state)
        },
    },
})
function getshopDataFn(state) {
    if (judgeNotEmpty(state.shopData)) {
        const shopData = Storage.get('shopData')
        if (judgeNotEmpty(shopData)) {
            return { id: '', token: '' }
        } else {
            state.shopData = shopData
            return shopData
        }
    } else {
        return state.shopData
    }
}
/**
 * 判断shopData是否为空
 * @param {*} obj
 */
function judgeNotEmpty(shopData) {
    if (JSON.stringify(shopData) === '{}' || JSON.stringify(shopData) === 'null') return true
    if (Object.keys(shopData).length === 0) return true
    if (!shopData.id) return true
    return false
}
